import React, {useState,useEffect} from "react";
import {trim} from "lodash";
import Modal from "antd/lib/modal";
import Form from "antd/lib/form";
import Input from "antd/lib/input";
import Checkbox from "antd/lib/checkbox";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {UserProfile} from "@/components/proptypes";
import notification from "@/services/notification";
import {currentUser} from "@/services/auth";
import Customer from "@/services/customer";
import Enums from "@/services/enums";
import moment from "moment";

function CreateCustomersDialog({ customers, dialog }) {
  const [dataLoaded, setDataLoaded] = useState(customers.id ===0 ? true : false);
  const [code, setCode] = useState("");
  const [name, setName] = useState("");
  const [representative, setrepresentative] = useState("");
  const [mobile, setmobile] = useState("");
  const [address, setaddress] = useState("");
  const [is_active, setis_active] = useState(true);
  const [isValid, setIsValid] = useState(false);
  const [saveInProgress, setSaveInProgress] = useState(false);
  const isCreateCustomersEnabled = useState(true);//policy.isAdmin() || policy.isDefault();

  useEffect(() => {
    if (customers.id === 0){
        let item = {
          tblname: "customers",
          bill_date: moment(),
          type: 0,
          tblfield: "strcustomercode",
        }
        Enums.getcode(item).then(data => {
          setCode(data[0].code);
          setDataLoaded(true);
        })
          .catch(error => {
            setDataLoaded(true);
          });
    }else{
        setCode(customers.strcustomercode);
        setName(customers.strcustomername);
        setrepresentative(customers.representative);
        setmobile(customers.mobile);
        setaddress(customers.address);
        setis_active(customers.blnisinactive);
        setDataLoaded(true);
      }
  }, [customers]);

  // function handleCodeChange(event) {
  //   const value = trim(event.target.value);
  //   setCode(value);
  //   setIsValid(value !== "" && name !== "");
  // }

  function handleis_activeChange(event) {
    const value = event.target.checked;
    setis_active(value);
    setIsValid(code !== "" && name !== "");
  }
  function handleNameChange(event) {
    const value = trim(event.target.value);
    setName(value);
    setIsValid(value !== "" && code !== "" );
  }
  function handlerepresentativeChange(event) {
    const value = trim(event.target.value);
    setrepresentative(value);
    setIsValid(code !== "" && name !== "" );
  }
  function handlemobileChange(event) {
    const value = trim(event.target.value);
    setmobile(value);
    setIsValid(code !== "" && name !== "" );
  }
  function handleaddressChange(event) {
    const value = trim(event.target.value);
    setaddress(value);
    setIsValid(code !== "" && name !== "" );
  }
  function handleSubmit() {
    setSaveInProgress(true);
   let data={id: customers.id,//
            userid: currentUser.id,//--操作员ID
            strcustomercode: code,
            strcustomername: name,
            representative: representative,
            mobile: mobile,
            address: address,
            blnisinactive: is_active,}
    if(customers.id===0) {
      Customer.createcustomer(data)
        .then(() => {
          dialog.close({ success: true});
        })
        .catch(error => {
          notification.error(error.response.data.message, error.detailedMessage);
          setSaveInProgress(false);
        });
    }else{
      Customer.savecustomer(data)
        .then(() => {
          dialog.close({ success: true});
        })
        .catch(error => {
          notification.error(error.response.data.message, error.detailedMessage);
          setSaveInProgress(false);
        });
    }
  }
  return (
    <Modal
      {...dialog.props}
      {...(isCreateCustomersEnabled ? {} : { footer: null })}
      title="客户管理"
      width={document.querySelector('body').offsetWidth*0.6}
      okText="保存"
      cancelText="取消"
      okButtonProps={{
        disabled: !isValid || saveInProgress,
        loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      cancelButtonProps={{
        disabled: saveInProgress,
      }}
      onOk={handleSubmit}
      closable={!saveInProgress}
      maskClosable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      {dataLoaded && (
      <DynamicComponent name="CreateCustomersDialogExtra" disabled={!isCreateCustomersEnabled}>
      <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
        {/* <Form.Item style={{ marginBottom: 5 }} label="单位编码" required={true}>
        <Input
          value={code}
          onChange={handleCodeChange}
          placeholder="单位编码"
          disabled={saveInProgress}
          autoFocus
        />
        </Form.Item> */}
        <Form.Item style={{ marginBottom: 5 }} label="单位名称" required={true}>
        <Input
          value={name}
          onChange={handleNameChange}
          placeholder="单位名称"
          disabled={saveInProgress}
        />
        </Form.Item>
        <Form.Item style={{ marginBottom: 5 }} label="联系人">
        <Input
          value={representative}
          onChange={handlerepresentativeChange}
          placeholder="联系人"
          disabled={saveInProgress}
        />
        </Form.Item>
        <Form.Item style={{ marginBottom: 5 }} label="电话">
        <Input
          value={mobile}
          onChange={handlemobileChange}
          placeholder="电话"
          disabled={saveInProgress}
        />
        </Form.Item>
        <Form.Item style={{ marginBottom: 5 }} label="地址">
        <Input
          value={address}
          onChange={handleaddressChange}
          placeholder="地址"
          disabled={saveInProgress}
        />
        </Form.Item>
        <Form.Item style={{ marginBottom: 5 }} label="启用">
        <Checkbox
          checked ={is_active}
          onChange={handleis_activeChange}
          disabled={saveInProgress}
          autoFocus
        />
        </Form.Item>
      </Form>
      </DynamicComponent>
      )}
    </Modal>
  );
}

CreateCustomersDialog.propTypes = {
  Customers: UserProfile.isRequired,
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateCustomersDialog);
